﻿using System;
using System.Data;
using System.Web;
using System.IO;

namespace Common.Util
{
    /// <summary>
    ///1.开头是不留空，以行为单位;
    ///2.可含或不含列名，含列名则居文件第一行;
    ///3.一行数据不垮行，无空行;
    ///4.以半角逗号作分隔符，列为空也要表达其存在;
    ///5.列内容如存在"逗号,换行符,双引号,字段前后包含有空格"，则用半角引号（即""）将该字段值包含起来;
    ///6.文件读写时引号，逗号操作规则互逆;内码格式不限，可为ASCII、Unicode或者其他。
    /// </summary>
    public class CSVhelper
    {
        public CSVhelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 读取CSV
        /// </summary>
        /// <param name="strpath"></param>
        /// <returns></returns>
        public DataTable ReadCSV(string strpath)
        {
            string _tablename = strpath.Substring(strpath.LastIndexOf("\\") + 1);
            string tablename = _tablename.Substring(0, _tablename.LastIndexOf("."));
            int intColCount = 0;
            bool blnFlag = true;
            string strline;
            string[] aryline;
            DataTable mydt = new DataTable(tablename);
            DataColumn mydc;
            DataRow mydr;
            System.IO.StreamReader mysr = new System.IO.StreamReader(strpath, System.Text.Encoding.Default);
            while ((strline = mysr.ReadLine()) != null)
            {

                aryline = strline.Split(new char[] { ',' });
                if (blnFlag)
                {
                    blnFlag = false;
                    intColCount = aryline.Length;
                    for (int i = 0; i < aryline.Length; i++)
                    {
                        mydc = new DataColumn(aryline[i]);
                        mydt.Columns.Add(mydc);
                    }
                }
                else
                {
                    mydr = mydt.NewRow();
                    for (int i = 0; i < intColCount; i++)
                    {
                        mydr[i] = ConvertToSaveCell(aryline[i], 1);
                    }
                    mydt.Rows.Add(mydr);
                }
            }
            return mydt;

        }

        /// <summary>
        /// 写入CSV
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="filename"></param>
        public void WriteCSV(DataTable tb)
        {
            string data = "";
            HttpContext.Current.Response.Clear();
            System.IO.StringWriter sw = new System.IO.StringWriter();
            //写出列名
            foreach (DataColumn column in tb.Columns)
            {
                data += column.ColumnName + ",";
            }
            data = data.Substring(0, data.Length - 1);
            sw.WriteLine(data);
            data = "";
            //写出数据
            foreach (DataRow row in tb.Rows)
            {
                foreach (DataColumn column in tb.Columns)
                {
                    data += ConvertToSaveCell(row[column].ToString(), 0) + ",";
                }
                data = data.Substring(0, data.Length - 1);
                sw.WriteLine(data);
                data = "";
            }
            sw.Close();

            //"http://" + HttpContext.Current.Request.UrlReferrer.Authority + "/WebSite/PerFile/tempimg/" + this.HiddenField1.Value + ".png";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode((tb.TableName + ".csv"), System.Text.Encoding.UTF8));

            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            HttpContext.Current.Response.Write(sw);

            HttpContext.Current.Response.End();

        }

        /// <summary>
        /// 转化中特殊格式的处理
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="i">0:tocsv;1:formcsv</param>
        /// <returns></returns>
        private string ConvertToSaveCell(string cell, int i)
        {
            if (i == 0)
            {
                cell = cell.Replace("\"", "\"\"");
                if (cell.IndexOf(",") >= 0 || cell.IndexOf("\"") >= 0)
                {
                    cell = "\"" + cell + "\"";
                }
                if (cell.IndexOf(",") >= 0)
                {
                    cell = cell.Replace(",", "，");
                }
            }
            else
            {
                if (cell.IndexOf("，") >= 0 || cell.IndexOf("\"") >= 0)
                {
                    if (cell.Substring(0, 1) == "\"" && cell.Substring(cell.Length - 1) == "\"")
                    {
                        cell = cell.Substring(1, cell.Length - 2);
                    }
                    if (cell.IndexOf("，") >= 0)
                    {
                        cell = cell.Replace("，", ",");
                    }
                }
                cell = cell.Replace("\"\"", "\"");
            }
            return cell;
        }

    }
}